package com.wusiwei.security;

import com.wusiwei.entity.User;
import com.wusiwei.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * UserDetailsService实现，用于Spring Security认证
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    /**
     * 默认管理员密码，只在数据库中不存在admin用户时使用
     * 密码为BCrypt加密格式，可在配置文件中自定义
     */
    @Value("${admin.default-password:$2a$10$i4tZyuujnuYgP/.GCTbQBui35Fuak/tFwJ5Teu1fvsv1PpuY9MZ4q}")
    private String defaultAdminPassword;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("尝试加载用户: {}", username);

        // 先从数据库查找用户
        User user = userService.findByUsername(username);

        // 如果是admin且数据库中不存在，使用默认admin账户
        if ("admin".equals(username) && user == null) {
            log.info("使用默认admin账户");
            return createAdminUserDetails();
        }

        if (user == null) {
            log.error("用户不存在: {}", username);
            throw new UsernameNotFoundException("用户名不存在");
        }

        log.info("用户已找到: {}", username);
        return createUserDetails(user);
    }

    /**
     * 创建默认的admin账户
     */
    private UserDetails createAdminUserDetails() {
        List<SimpleGrantedAuthority> authorities = Collections.singletonList(
                new SimpleGrantedAuthority("ROLE_ADMIN"));

        return new org.springframework.security.core.userdetails.User(
                "admin",
                defaultAdminPassword, // 使用配置的密码
                true, true, true, true,
                authorities);
    }

    /**
     * 根据User实体创建UserDetails
     */
    private UserDetails createUserDetails(User user) {
        // 不再使用realName作为角色，改为固定角色"ROLE_USER"
        List<SimpleGrantedAuthority> authorities = Collections.singletonList(
                new SimpleGrantedAuthority("ROLE_USER"));

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                true, true, true, true,
                authorities);
    }
} 